<script lang="ts" setup>
import { computed, onMounted, onUnmounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import { Page } from '@vben/common-ui';
import { updatePreferences } from '@vben/preferences';
import { Col, Row, Select } from 'ant-design-vue';
import { useUserStore } from '@vben/stores';
import {
  getAgeSexStatistics,
  getAllOrgList,
  getClickStatistics,
  getEducationLevelStatistics,
  getHobbyStatistics,
  getJoinYearStatistics,
  getPoliticalOutlookStatistics,
} from '#/api/largeVisualScreen/B';
import { requestClient } from '#/api/request.js';

// @ts-ignore: JavaScript module without types
import useDraw from '../useDraw.js';
import centerOne from './components/centerOne.vue';
import centerTwo from './components/centerTwo.vue';
import leftOne from './components/leftOne.vue';
import leftThree from './components/leftThree.vue';
import leftTwo from './components/leftTwo.vue';
import rightOne from './components/rightOne.vue';
import rightTwo from './components/rightTwo.vue';

// ===== 类型定义 =====
interface HobbyData {
  indicators: { max: number; name: string }[];
  series: {
    data: Array<{ name: string; value: number[]; }>;
    type: string;
  }[];
}

// ===== 基础配置和工具 =====
const userStore = useUserStore();
const router = useRouter();
const { appRef, calcRate, windowDraw, unWindowDraw } = useDraw();

// ===== 页面基础状态 =====
const loading = ref(false);
const title = ref('数据大屏B');
const enterpriseId = ref();

// 判断是否是管理员
const isAdmin = computed(() => {
  return userStore.$state.userRoles?.some(role => role === 'superadmin');
});

// ===== 用户和组织管理 =====
const userList = ref<{ userId: string; nickName: string; enterpriseId: number }[]>([]);
const objectsList = ref();

// 获取用户列表
const getUserList = async () => {
  const res = await requestClient.get('/system/user/list');
  userList.value = res.rows.filter((item: any) => item.userId !== 1);
};

// 获取组织列表
const getObjectList = async () => {
  const res = (await getAllOrgList()) as { orgList: any[] };
  res.orgList.unshift({ orgId: 0, orgName: '全部' });
  objectsList.value = res.orgList;
};

// ===== 入会年份统计模块 =====
const joinYearOrgId = ref(0);
const joinYearData = ref<{ seriesData: any[]; xData: any[]; }>({
  xData: [],
  seriesData: []
});
let joinYearTimer: ReturnType<typeof setInterval>;

// 获取入会年份统计数据
const fetchJoinYearStatistics = async () => {
  const res = await getJoinYearStatistics(joinYearOrgId.value);
  joinYearData.value.xData = res.year;
  joinYearData.value.seriesData = res.seriesData;
};

// 处理入会年份组织变更
const handleJoinYearOrgChange = () => {
  if (joinYearTimer) clearInterval(joinYearTimer);
  fetchJoinYearStatistics();
  joinYearTimer = setInterval(fetchJoinYearStatistics, 5000);
};

// ===== 教育水平统计模块 =====
const educationOrgId = ref(0);
const educationData = ref<{ seriesData: number[]; xData: string[]; }>({
  xData: [],
  seriesData: []
});
let educationTimer: ReturnType<typeof setInterval>;

// 获取教育水平统计数据
const fetchEducationStatistics = async () => {
  const res = await getEducationLevelStatistics(educationOrgId.value.toString());
  educationData.value.xData = res.xData;
  educationData.value.seriesData = res.seriesData;
};

// 处理教育水平组织变更
const handleEducationOrgChange = () => {
  if (educationTimer) clearInterval(educationTimer);
  fetchEducationStatistics();
  educationTimer = setInterval(fetchEducationStatistics, 5000);
};

// ===== 兴趣爱好统计模块 =====
const hobbyOrgId = ref(0);
const hobbyData = ref<HobbyData>({
  indicators: [
    { name: '阅读', max: 100 },
    { name: '运动', max: 100 },
    { name: '音乐', max: 100 },
    { name: '旅游', max: 100 },
    { name: '其他', max: 100 },
  ],
  series: [
    {
      type: 'radar',
      data: [
        { value: [0, 0, 0, 0, 0], name: '爱好分布' },
      ],
    },
  ],
});
let hobbyTimer: ReturnType<typeof setInterval>;

// 获取兴趣爱好统计数据
const fetchHobbyStatistics = async () => {
  try {
    const res = await getHobbyStatistics(hobbyOrgId.value.toString());
    const maxValue = Math.max(...res.max, 100);
    hobbyData.value = {
      indicators: res.name.map((name: string) => ({ name, max: maxValue })),
      series: [
        {
          type: 'radar',
          data: [{ value: res.max, name: '爱好分布' }],
        },
      ],
    };
  } catch (error) {
    console.error('获取兴趣爱好统计数据失败:', error);
  }
};

// 处理兴趣爱好组织变更
const handleHobbyOrgChange = () => {
  if (hobbyTimer) clearInterval(hobbyTimer);
  fetchHobbyStatistics();
  hobbyTimer = setInterval(fetchHobbyStatistics, 5000);
};

// ===== 点击量统计模块 =====
const clickOrgId = ref(0);
const clickData = ref<{
  seriesData: number[];
  xData: string[];
}>({
  xData: [],
  seriesData: [],
});
let clickTimer: ReturnType<typeof setInterval>;

// 获取点击量统计数据
const fetchClickStatistics = async () => {
  const res = await getClickStatistics(clickOrgId.value.toString());
  clickData.value.xData = res.xData;
  clickData.value.seriesData = res.seriesData;
};

// 处理点击量组织变更
const handleClickOrgChange = () => {
  if (clickTimer) clearInterval(clickTimer);
  fetchClickStatistics();
  clickTimer = setInterval(fetchClickStatistics, 5000);
};

// ===== 政治面貌统计模块 =====
const politicalOrgId = ref(0);
const politicalData = ref<{
  name: string;
  value: number;
}[]>([]);
let politicalTimer: ReturnType<typeof setInterval>;

// 获取政治面貌统计数据
const fetchPoliticalStatistics = async () => {
  const res = await getPoliticalOutlookStatistics(politicalOrgId.value.toString());
  politicalData.value = res.data;
};

// 处理政治面貌组织变更
const handlePoliticalOrgChange = () => {
  if (politicalTimer) clearInterval(politicalTimer);
  fetchPoliticalStatistics();
  politicalTimer = setInterval(fetchPoliticalStatistics, 5000);
};

// ===== 年龄性别统计模块 =====
const ageSexOrgId = ref(0);
const ageSexData = ref<{
  femaleData: number[];
  maleData: number[];
  unknownData: number[];
  xData: string[];
}>({
  xData: [],
  maleData: [],
  femaleData: [],
  unknownData: [],
});
let ageSexTimer: ReturnType<typeof setInterval>;

// 获取年龄性别统计数据
const fetchAgeSexStatistics = async () => {
  const res = await getAgeSexStatistics(ageSexOrgId.value.toString());
  ageSexData.value.xData = res.age;
  ageSexData.value.maleData = res.maleData;
  ageSexData.value.femaleData = res.femaleData;
  ageSexData.value.unknownData = res.unknownData;
};

// 处理年龄性别组织变更
const handleAgeSexOrgChange = () => {
  if (ageSexTimer) clearInterval(ageSexTimer);
  fetchAgeSexStatistics();
  ageSexTimer = setInterval(fetchAgeSexStatistics, 5000);
};

// ===== 活动数据模块 =====
const centerTwoData = ref({
  header: ['活动主题', '活动时间', '活动类型', '参与人数', '活动成果'],
  data: [
    ['主题1', '2025-5-29', '个人', '500', '50'],
    ['主题2', '2025-6-15', '团队', '300', '30'],
    ['主题3', '2025-7-10', '个人', '450', '45'],
    ['主题4', '2025-8-20', '团队', '600', '60'],
    ['主题5', '2025-9-05', '个人', '400', '40'],
    ['主题6', '2025-10-12', '团队', '550', '55'],
    ['主题7', '2025-11-18', '个人', '350', '35'],
    ['主题8', '2025-12-25', '团队', '700', '70'],
  ],
});

// ===== 工具方法 =====
// 关闭加载状态
function closeLoading() {
  setTimeout(() => (loading.value = false), 2000);
}

// 处理ESC键事件
function handleEscKeydown(event: KeyboardEvent) {
  if (event.key === 'Escape') {
    router.back();
    updateScreenPreferences('default');
  }
}

// 更新屏幕偏好设置
function updateScreenPreferences(mode: 'default' | 'full') {
  return updatePreferences({
    app: { layout: mode === 'full' ? 'full-content' : 'sidebar-nav' },
    header: { enable: mode !== 'full' },
    sidebar: { collapsed: mode === 'full' },
    tabbar: { enable: false },
  });
}

// ===== 页面生命周期管理 =====
// 初始化页面
const init = async () => {
  closeLoading();
  calcRate();
  windowDraw();
  await getObjectList();
  window.addEventListener('keydown', handleEscKeydown);
  updateScreenPreferences('full');

  // 启动所有图表的定时器
  handleJoinYearOrgChange();
  handleEducationOrgChange();
  handleHobbyOrgChange();
  handleClickOrgChange();
  handlePoliticalOrgChange();
  handleAgeSexOrgChange();
};

// 清理资源
const cleanup = () => {
  unWindowDraw();
  window.removeEventListener('keydown', handleEscKeydown);

  // 清理所有定时器
  if (joinYearTimer) clearInterval(joinYearTimer);
  if (educationTimer) clearInterval(educationTimer);
  if (hobbyTimer) clearInterval(hobbyTimer);
  if (clickTimer) clearInterval(clickTimer);
  if (politicalTimer) clearInterval(politicalTimer);
  if (ageSexTimer) clearInterval(ageSexTimer);
};

// ===== 组件挂载和卸载 =====
onMounted(async () => {
  // 管理员初始化
  if (isAdmin.value) {
    await getUserList();
    enterpriseId.value = userList?.value[0]?.enterpriseId;
  }
  await getObjectList();

  // 初始化兴趣爱好数据
  fetchHobbyStatistics();

  // 启动页面
  init();
});

onUnmounted(cleanup);
</script>

<template>
  <Page :auto-content-height="true" class="map-container">
    <div id="map-box" ref="appRef">
      <div class="bg">
        <dv-loading v-if="loading">Loading...</dv-loading>
        <div v-else style="width: 100%; height: 100%">
          <!-- 页面头部 -->
          <div class="header">
            <div class="move-line"></div>
            <div class="header-title">{{ title }}</div>
            <img class="header-bg" src="../../../assets/header-04.png" />
            <Select v-if="isAdmin" v-model:value="enterpriseId" placeholder="请选择企业" class="org-select1"
              @change="handleJoinYearOrgChange">
              <Select.Option v-for="org in userList" :key="org.userId" :value="org.enterpriseId">
                {{ org.nickName }}
              </Select.Option>
            </Select>
          </div>

          <!-- 主要内容区域 -->
          <Row :gutter="[10, 10]" style="height: calc(100% - 60px); padding: 20px 0 0">
            <!-- 左侧图表区域 -->
            <Col :span="7">
            <!-- 入会年份统计 -->
            <dv-border-box-8 style="height: 32%">
              <div class="chart-header">
                <div>入会年份统计</div>
                <Select v-model:value="joinYearOrgId" placeholder="请选择组织" class="org-select"
                  @change="handleJoinYearOrgChange">
                  <Select.Option v-for="org in objectsList" :key="org.orgId" :value="org.orgId">
                    {{ org.orgName }}
                  </Select.Option>
                </Select>
              </div>
              <leftOne :chart-data="joinYearData" />
            </dv-border-box-8>

            <!-- 教育水平统计 -->
            <dv-border-box-8 style="height: 33%; margin: 2% 0">
              <div class="chart-header">
                <div>教育水平统计</div>
                <Select v-model:value="educationOrgId" placeholder="请选择组织" class="org-select"
                  @change="handleEducationOrgChange">
                  <Select.Option v-for="org in objectsList" :key="org.orgId" :value="org.orgId">
                    {{ org.orgName }}
                  </Select.Option>
                </Select>
              </div>
              <leftTwo :chart-data="educationData" />
            </dv-border-box-8>

            <!-- 兴趣爱好统计 -->
            <dv-border-box-8 style="height: 32%">
              <div class="chart-header">
                <div>各类爱好人数统计</div>
                <Select v-model:value="hobbyOrgId" placeholder="请选择组织" class="org-select"
                  @change="handleHobbyOrgChange">
                  <Select.Option v-for="org in objectsList" :key="org.orgId" :value="org.orgId">
                    {{ org.orgName }}
                  </Select.Option>
                </Select>
              </div>
              <leftThree :chart-data="hobbyData" />
            </dv-border-box-8>
            </Col>

            <!-- 中间图表区域 -->
            <Col :span="10">
            <!-- 点击量统计 -->
            <dv-border-box-8 style="height: 66%">
              <div class="chart-header">
                <div>点击量</div>
                <Select v-model:value="clickOrgId" placeholder="请选择组织" class="org-select"
                  @change="handleClickOrgChange">
                  <Select.Option v-for="org in objectsList" :key="org.orgId" :value="org.orgId">
                    {{ org.orgName }}
                  </Select.Option>
                </Select>
              </div>
              <centerOne :chart-data="clickData" />
            </dv-border-box-8>

            <!-- 活动相关统计 -->
            <div style="width: 100%; height: 32%; margin: 2% 0">
              <Row class="h-full w-full">
                <!-- 组织开展活动 -->
                <Col :span="9">
                <dv-border-box-8>
                  <div class="chart-header">
                    <div>组织开展活动</div>
                    <Select v-model:value="joinYearOrgId" placeholder="请选择组织" class="org-select"
                      @change="handleJoinYearOrgChange">
                      <Select.Option v-for="org in objectsList" :key="org.orgId" :value="org.orgId">
                        {{ org.orgName }}
                      </Select.Option>
                    </Select>
                  </div>
                  <div class="flex flex-col items-center">
                    <div>
                      <dv-decoration-9 style="width: 90px; height: 90px">
                        66
                      </dv-decoration-9>
                      <div>开展活动数量</div>
                    </div>
                    <div class="mt-4">
                      <dv-decoration-9 style="width: 90px; height: 90px">
                        66
                      </dv-decoration-9>
                      <div>活动参与人数</div>
                    </div>
                  </div>
                </dv-border-box-8>
                </Col>

                <!-- 平台活动开展数据 -->
                <Col :span="15" style="padding-left: 12px">
                <dv-border-box-8>
                  <div class="chart-header">
                    <div>平台活动开展数据</div>
                  </div>
                  <centerTwo :chart-data="centerTwoData" />
                </dv-border-box-8>
                </Col>
              </Row>
            </div>
            </Col>

            <!-- 右侧图表区域 -->
            <Col :span="7">
            <!-- 政治面貌统计 -->
            <dv-border-box-8 style="height: 32%">
              <div class="chart-header">
                <div>政治面貌统计</div>
                <Select v-model:value="politicalOrgId" placeholder="请选择组织" class="org-select"
                  @change="handlePoliticalOrgChange">
                  <Select.Option v-for="org in objectsList" :key="org.orgId" :value="org.orgId">
                    {{ org.orgName }}
                  </Select.Option>
                </Select>
              </div>
              <rightOne :chart-data="politicalData" />
            </dv-border-box-8>

            <!-- 年龄性别统计 -->
            <dv-border-box-8 style="height: 66%; margin: 2% 0">
              <div class="chart-header">
                <div>年龄区间性别统计</div>
                <Select v-model:value="ageSexOrgId" placeholder="请选择组织" class="org-select"
                  @change="handleAgeSexOrgChange">
                  <Select.Option v-for="org in objectsList" :key="org.orgId" :value="org.orgId">
                    {{ org.orgName }}
                  </Select.Option>
                </Select>
              </div>
              <rightTwo :chart-data="ageSexData" />
            </dv-border-box-8>
            </Col>
          </Row>
        </div>
      </div>
    </div>
  </Page>
</template>

<style lang="scss" scoped>
// ===== 容器样式 =====
.map-container {
  width: 100%;
  height: 100%;
  padding: 0 !important;
  margin: 0 !important;
  background-color: black;

  :deep(.h-full) {
    padding: 0 !important;
  }

  #map-box {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 1920px;
    height: 1080px;
    color: #d3d6dd;
    background-color: #ffebcd;
    transform: translate(-50%, -50%);
    transform-origin: left top;

    .bg {
      box-sizing: border-box;
      width: 100%;
      height: 100%;
      padding: 12px 12px 0;
      background-image: url('../../../assets/pageBg.png');
      background-position: center center;
      background-size: cover;
    }
  }
}

// ===== 头部样式 =====
.header {
  position: relative;
  width: 100%;
  height: 50px;

  @keyframes move-left-to-right {
    from {
      transform: translateX(0);
    }

    to {
      transform: translateX(calc(100vw - 106px));
    }
  }

  .move-line {
    position: absolute;
    bottom: -11px;
    left: 0;
    width: 106px;
    height: 28px;
    background: url('../../../assets/line-bg.png') no-repeat;
    background-size: 100% 100%;
    animation: move-left-to-right 4s linear infinite;
  }

  .header-title {
    min-width: 250px;
    margin: 0 50px;
    font-size: 20px;
    font-weight: 900;
    line-height: 2.8rem;
    color: transparent;
    text-align: center;
    letter-spacing: 4px;
    background-image: linear-gradient(92deg,
        #0072ff 0%,
        #00eaff 48.8525%,
        #01aaff 100%);
    background-clip: text;
  }

  .header-bg {
    position: absolute;
    top: 0;
    right: 0;
    left: 0;
    z-index: 0;
    width: 100%;
    height: 3.84rem;
    margin: 0 auto;
  }
}

// ===== 图表样式 =====
.chart-header {
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px;
  border-radius: 4px;
}

.chart-types {
  display: flex;
  gap: 20px;
}

.chart-type-item {
  position: relative;
  padding: 8px 16px;
  overflow: hidden;
  font-size: 14px;
  color: rgb(0 242 254 / 70%);
  cursor: pointer;
  border: 1px solid transparent;
  border-radius: 4px;
  transition: all 0.3s ease;

  &::before {
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 2px;
    content: '';
    background: linear-gradient(90deg, transparent, rgb(0 242 254 / 80%));
    transition: 0.5s;
  }

  &:hover {
    color: rgb(0 242 254 / 100%);
    border-color: rgb(0 242 254 / 30%);
    box-shadow: 0 0 10px rgb(0 242 254 / 10%);

    &::before {
      left: 100%;
    }
  }

  &.active {
    color: #fff;
    background: linear-gradient(90deg,
        rgb(0 242 254 / 30%) 0%,
        rgb(0 242 254 / 10%) 100%);
    border-color: rgb(0 242 254 / 50%);
    box-shadow: 0 0 15px rgb(0 242 254 / 20%);
  }
}

// ===== 选择器样式 =====
.org-select {
  width: 160px;

  :deep(.ant-select-selector) {
    color: #fff !important;
    background: rgb(1 36 86 / 50%) !important;
    border-color: rgb(0 242 254 / 30%) !important;
  }

  :deep(.ant-select-arrow) {
    color: rgb(0 242 254 / 70%);
  }

  &:hover {
    :deep(.ant-select-selector) {
      border-color: rgb(0 242 254 / 80%) !important;
      box-shadow: 0 0 10px rgb(0 242 254 / 20%) !important;
    }
  }
}

.org-select1 {
  width: 160px;
  position: absolute;
  left: 0;
  top: 0;

  :deep(.ant-select-selector) {
    color: #fff !important;
    background: rgb(1 36 86 / 50%) !important;
    border-color: rgb(0 242 254 / 30%) !important;
  }

  :deep(.ant-select-arrow) {
    color: rgb(0 242 254 / 70%);
  }

  &:hover {
    :deep(.ant-select-selector) {
      border-color: rgb(0 242 254 / 80%) !important;
      box-shadow: 0 0 10px rgb(0 242 254 / 20%) !important;
    }
  }
}

// ===== 废弃样式（保留以防需要） =====
.map-container-box {
  height: calc(100% - 50px);
  padding-top: 10px;
  padding-bottom: 10px;

  .top-chartBox {
    display: flex;
    height: 60%;

    .top-left {
      width: 25%;
      height: 100%;

      .top-left-top {
        height: 50%;
      }

      .top-left-bottom {
        height: 50%;
      }
    }

    .top-center {
      width: 50%;
      height: 100%;
    }

    .top-right {
      width: 25%;
      height: 100%;

      .top-right-top {
        height: 50%;
      }

      .top-right-bottom {
        height: 50%;
      }
    }
  }

  .bottom-chartBox {
    display: flex;
    height: 40%;

    .bottom-left {
      width: 50%;
      height: 100%;
    }

    .bottom-right {
      width: 50%;
      height: 100%;
    }
  }
}
</style>
